<!DOCTYPE html>
<html>
        
        <head>
                <title>
                        Web通信demo
                </title>
                <link rel="stylesheet" href="vendor/bootstrap.min.css" />
                <script src="vendor/jquery.js">
                </script>
                <script src="vendor/socket.io.js">
                </script>
                <script src="vendor/adapter.js">
                </script>
                <script src="AgoraRTCSDK-1.8.1.js">
                </script>
        </head>
        
        <body>
                <div id="div_device" class="panel panel-default">
                        <div class="select">
                                <label for="audioSource">
                                        Audio source:
                                </label>
                                <select id="audioSource">
                                </select>
                        </div>
                        <div class="select">
                                <label for="videoSource">
                                        Video source:
                                </label>
                                <select id="videoSource">
                                </select>
                        </div>
                </div>
                <div id="div_join" class="panel panel-default">
                        <div class="panel-body">
                                Key:
                                <input id="key" type="text" size="36" value="d51a586509bb4992a00b72a453df77a9" />
                                Channel:
                                <input id="channel" type="text" size="4" value="youxuanit" />
                                <button id="join" class="btn btn-primary" onclick="join()">
                                        Join
                                </button>
                                <button id="leave" class="btn btn-primary" onclick="leave()">Leave</button>
                        </div>
                </div>
                <div id="video" style="width:1022px;margin:0 auto;">
                        <div id="agora_local" style="float:right;width:280px;height:200px;display:inline-block;">
                        </div>
                </div>
<script language="javascript">
                        
var userid = (Math.random()*100).toFixed();
var client, localStream, camera, microphone;

var audioSelect = document.querySelector('select#audioSource');
var videoSelect = document.querySelector('select#videoSource');

function join() {
  document.getElementById("join").disabled = true;
  document.getElementById("video").disabled = true;
  // for dynamic key start
  var dynamic_key;
  console.log("Try to get dynamic key");
  var use_https = ('https:' == document.location.protocol ? true : false);
  if (use_https) {
    var url_str = "https://192.168.1.21:8888/agora/php/key.php?uid=" + userid + "&channelName=" + channel.value;
  } else {
    alert('请使用https部署网站');return false;
  }
  $.ajax({
    url: url_str,
    error: function() {
      console.log("Failed to get 192.168.1.21 dynamic key");
    },
    success: function(response) {
//      console.log(response.key);  dynamic_key = response.key;
      console.log("successful to get 192.168.1.21 dynamic key %s <===>" ,response);
      dynamic_key = response;

  //该方法创建和返回针对实时通信用户场景的客户端对象，包含音视频聊天和会议。该方法在每次会话里仅调用一次。
  //var client = AgoraRTC.createRtcClient(); 
  client = AgoraRTC.createLiveClient();
  client.init(dynamic_key, function () {
    console.log("AgoraRTC client initialized");
    client.join(channel.value, userid, function(uid) {
      console.log("User " + uid + " join channel successfully");
        camera = videoSource.value;
        microphone = audioSource.value;
        localStream = AgoraRTC.createStream({streamID: uid, audio: true, cameraId: camera, microphoneId: microphone, video: true, screen: false});
        localStream.setVideoProfile('720p_3');
        localStream.init(function() {
          console.log("getUserMedia successfully");
          localStream.play('agora_local');

          client.publish(localStream, function (err) {
            console.log("Publish local stream error: " + err);
          });

          client.on('stream-published', function (evt) {
            console.log("Publish local stream successfully");
          });
        }, function (err) {
          console.log("getUserMedia failed", err);
        });
    }, function(err) {
      console.log("Join channel failed", err);
    });
  }, function (err) {
    console.log("AgoraRTC client init failed", err);
  });

  client.on('stream-added', function (evt) {
    var stream = evt.stream;
    console.log("New stream added: " + stream.getId());
    console.log("Subscribe ", stream);
    //订阅远程音视频流(subscribe)
    client.subscribe(stream, function (err) {
      console.log("Subscribe stream failed", err);
    });
  });

  client.on('stream-subscribed', function (evt) {
    var stream = evt.stream;
    console.log("Subscribe remote stream successfully: " + stream.getId());
    if ($('div#video #agora_remote'+stream.getId()).length === 0) {
      $('div#video').append('<div id="agora_remote'+stream.getId()+'" style="float:left; width:810px;height:607px;display:inline-block;"></div>');
    }
    stream.play('agora_remote' + stream.getId());
  });

  client.on('stream-removed', function (evt) {
    var stream = evt.stream;
    stream.stop();
    $('#agora_remote' + stream.getId()).remove();
    console.log("Remote stream is removed " + stream.getId());
  });

  client.on('peer-leave', function (evt) {
    var stream = evt.stream;
    stream.stop();
    $('#agora_remote' + stream.getId()).remove();
    console.log(evt.uid + " leaved from this channel");
  });
  // for dynamic key end
  }
  });
}

function leave() {
  document.getElementById("leave").disabled = true;
  client.leave(function () {
    console.log("Leavel channel successfully");
  }, function (err) {
    console.log("Leave channel failed");
  });
}

function publish() {
  document.getElementById("publish").disabled = true;
  client.publish(localStream, function (err) {
    console.log("Publish local stream error: " + err);
  });
}

function unpublish() {
  document.getElementById("publish").disabled = false;
  document.getElementById("unpublish").disabled = true;
  client.unpublish(localStream, function (err) {
    console.log("Unpublish local stream failed" + err);
  });
}

function getDevices() {
  AgoraRTC.getDevices(function (devices) {
    for (var i = 0; i !== devices.length; ++i) {
      var device = devices[i];
      var option = document.createElement('option');
      option.value = device.deviceId;
      if (device.kind === 'audioinput') {
        option.text = device.label || 'microphone ' + (audioSelect.length + 1);
        audioSelect.appendChild(option);
      } else if (device.kind === 'videoinput') {
        option.text = device.label || 'camera ' + (videoSelect.length + 1);
        videoSelect.appendChild(option);
      } else {
        console.log('Some other kind of source/device: ', device);
      }
    }
  });
}

audioSelect.onchange = getDevices;
videoSelect.onchange = getDevices;
getDevices();
</script>
</body>
</html>